package com.namo.cchapi.controller;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.namo.cchapi.entity.WechatMessageEntity;
import com.namo.cchapi.entity.WechatMessageTemplateEntity;
import com.namo.cchapi.entity.WechatUserOpenEntity;
import com.namo.cchapi.service.WechatService;
import com.namo.cchcommon.api.CommonResult;
import com.namo.cchcommon.api.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author WangXin
 * @date 2021/4/9 15:18
 */
@RestController()
@RequestMapping("/wechat")
public class WechatController {

    @Autowired
    WechatService wechatService;

    @Autowired
    Gson gson;

    /**
     * 获取消息模板
     * @return
     */
    @RequestMapping(value = "/template", method = RequestMethod.GET)
    public CommonResult<Object> getWechatTemplate() {
        List<WechatMessageTemplateEntity> wechatMessageTemplateEntity = null;
        try {
            wechatMessageTemplateEntity = wechatService.getTemplateList();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("错误");
        }
        return CommonResult.success((wechatMessageTemplateEntity));
    }

    /**
     * 获取用户开放信息
     * @return
     */
    @RequestMapping(value = "/open", method = RequestMethod.GET)
    public CommonResult<Object> getWechatTemplate(@RequestParam("code") String code) throws Exception {
        WechatUserOpenEntity userOpen = wechatService.getUserOpen(code);
        return CommonResult.success((userOpen));
    }




    /**
     * 请求示例
     * {
     *     "touser": "o67TR4pKosR2L6nF8YKsvuuMnY1Y",
     *     "template_id": "6Cbfy1XrJYsagXsIAvZT89YVxVtb92K_EKfFmwaMzRA",
     *     "page": "pages/index/index",
     *     "miniprogram_state": "developer",
     *     "data": {
     *         "name1": {
     *             "value": "wx"
     *         },
     *         "date2": {
     *             "value": "2019-11-25 14:00:00"
     *         },
     *         "thing3": {
     *             "value": "吃饭"
     *         }
     *     }
     * }
     * @param requestBody
     * @return
     */
    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public CommonResult<Object> sendMessage(@RequestBody String requestBody) {
        WechatMessageEntity wechatMessageEntity = null;
        try {
            wechatMessageEntity =  wechatService.sendMessage(gson.fromJson(requestBody,WechatMessageEntity.class));
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(e.getMessage());
        }
        return CommonResult.success(wechatMessageEntity);
    }
}
